package com.example.musicplayerbasedonservice

import android.app.*
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.*
import android.provider.MediaStore
import androidx.core.app.NotificationCompat
import android.net.Uri
import android.app.PendingIntent

class MusicService : Service() {

    private lateinit var mediaPlayer: MediaPlayer
    private lateinit var musicList: MutableList<Music>
    private var currentPosition = 0
    private val binder = MusicBinder()

    inner class MusicBinder : Binder() {
        fun getService(): MusicService = this@MusicService
    }

    override fun onCreate() {
        super.onCreate()
        mediaPlayer = MediaPlayer()
        musicList = getMusicList()
    }

    override fun onBind(intent: Intent): IBinder {
        return binder
    }



    private fun getMusicList(): MutableList<Music> {
        val musicList = mutableListOf<Music>()
        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST
        )
        val selection = "${MediaStore.Audio.Media.IS_MUSIC} != 0"
        val sortOrder = "${MediaStore.Audio.Media.TITLE} ASC"

        contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection,
            selection,
            null,
            sortOrder
        )?.use { cursor ->
            val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
            val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
            val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)

            while (cursor.moveToNext()) {
                val id = cursor.getLong(idColumn)
                val title = cursor.getString(titleColumn)
                val artist = cursor.getString(artistColumn)
                val contentUri = ContentUris.withAppendedId(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    id
                )
                musicList.add(Music(id, title, artist, contentUri))
            }
        }

        if (musicList.isEmpty()) {
            // 如果没有找到音乐，添加一个默认的"无音乐"项
            musicList.add(Music(-1, "No music found", "Unknown", Uri.EMPTY))
        }

        return musicList
    }

    fun play() {
        if (!mediaPlayer.isPlaying) {
            if (mediaPlayer.currentPosition > 0) {
                mediaPlayer.start()
            } else {
                playMusic(currentPosition)
            }
        }
    }

    fun pause() {
        if (mediaPlayer.isPlaying) {
            mediaPlayer.pause()
        }
    }

    fun stop() {
        mediaPlayer.stop()
        mediaPlayer.prepare()
        mediaPlayer.seekTo(0)
        currentPosition = 0
    }

    fun next() {
        currentPosition = (currentPosition + 1) % musicList.size
        playMusic(currentPosition)
    }

    fun previous() {
        currentPosition = if (currentPosition > 0) currentPosition - 1 else musicList.size - 1
        playMusic(currentPosition)
    }

    private fun playMusic(position: Int) {
        if (musicList.isEmpty()) {
            // 如果没有音乐可播放，直接返回
            return
        }
        mediaPlayer.reset()
        mediaPlayer.setDataSource(applicationContext, musicList[position].uri)
        mediaPlayer.prepare()
        mediaPlayer.start()
        showNotification(musicList[position].title)  // 这里调用了显示通知的方法
    }

    fun seekTo(position: Int) {
        mediaPlayer.seekTo(position)
    }

    fun getCurrentPosition(): Int = mediaPlayer.currentPosition

    fun getDuration(): Int = mediaPlayer.duration

    fun getCurrentMusicTitle(): String {
        return if (musicList.isNotEmpty()) {
            musicList[currentPosition].title
        } else {
            "No music available"
        }
    }

    private fun showNotification(songName: String) {
        val channelId = "MusicPlayerChannel"
        val channelName = "Music Player"
        val importance = NotificationManager.IMPORTANCE_DEFAULT  // 将重要性改为 DEFAULT

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, channelName, importance)
            notificationManager.createNotificationChannel(channel)
        }

        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)

        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle("Now Playing")
            .setContentText(songName)
            .setSmallIcon(android.R.drawable.ic_media_play)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build()

        startForeground(1, notification)
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.release()
    }
}

data class Music(val id: Long, val title: String, val artist: String, val uri: android.net.Uri)
